"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Badge } from "@/components/ui/badge"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  PlusIcon,
  SearchIcon,
  RefreshCwIcon,
  PlayIcon,
  PauseIcon,
  SettingsIcon,
  AlertTriangleIcon,
  CheckCircleIcon,
  XCircleIcon,
  WifiIcon,
  BatteryMediumIcon,
  DropletIcon,
  LeafIcon,
  BarChart3Icon,
  CloudIcon,
} from "lucide-react"
import DashboardLayout from "@/components/dashboard-layout"

// 模拟数据
const mockDevices = [
  {
    id: 1,
    name: "主水泵",
    type: "pump",
    location: "1号农田",
    status: "online",
    isRunning: false,
    lastActive: "10分钟前",
    batteryLevel: 85,
    signalStrength: "strong",
  },
  {
    id: 2,
    name: "1号电磁阀",
    type: "valve",
    location: "1号农田",
    status: "online",
    isRunning: true,
    lastActive: "正在运行",
    batteryLevel: 72,
    signalStrength: "medium",
  },
  {
    id: 3,
    name: "2号电磁阀",
    type: "valve",
    location: "2号农田",
    status: "online",
    isRunning: false,
    lastActive: "2小时前",
    batteryLevel: 65,
    signalStrength: "strong",
  },
  {
    id: 4,
    name: "施肥机",
    type: "fertilizer",
    location: "1号农田",
    status: "online",
    isRunning: false,
    lastActive: "1小时前",
    batteryLevel: 90,
    signalStrength: "strong",
  },
  {
    id: 5,
    name: "土壤湿度传感器",
    type: "sensor",
    location: "1号农田",
    status: "online",
    isRunning: true,
    lastActive: "正在运行",
    batteryLevel: 45,
    signalStrength: "medium",
  },
  {
    id: 6,
    name: "EC传感器",
    type: "sensor",
    location: "2号农田",
    status: "warning",
    isRunning: true,
    lastActive: "正在运行",
    batteryLevel: 30,
    signalStrength: "weak",
  },
  {
    id: 7,
    name: "PH传感器",
    type: "sensor",
    location: "1号农田",
    status: "offline",
    isRunning: false,
    lastActive: "1天前",
    batteryLevel: 10,
    signalStrength: "none",
  },
  {
    id: 8,
    name: "气象站",
    type: "weather",
    location: "农场中心",
    status: "online",
    isRunning: true,
    lastActive: "正在运行",
    batteryLevel: 80,
    signalStrength: "strong",
  },
]

const deviceTypes = [
  { value: "all", label: "全部设备" },
  { value: "pump", label: "水泵" },
  { value: "valve", label: "电磁阀" },
  { value: "fertilizer", label: "施肥机" },
  { value: "sensor", label: "传感器" },
  { value: "weather", label: "气象站" },
]

const locations = [
  { value: "all", label: "全部位置" },
  { value: "1号农田", label: "1号农田" },
  { value: "2号农田", label: "2号农田" },
  { value: "农场中心", label: "农场中心" },
]

export default function DevicesPage() {
  const [devices, setDevices] = useState(mockDevices)
  const [filterType, setFilterType] = useState("all")
  const [filterLocation, setFilterLocation] = useState("all")
  const [searchQuery, setSearchQuery] = useState("")

  const toggleDevice = (id) => {
    setDevices(devices.map((device) => (device.id === id ? { ...device, isRunning: !device.isRunning } : device)))
  }

  const filteredDevices = devices.filter((device) => {
    const matchesType = filterType === "all" || device.type === filterType
    const matchesLocation = filterLocation === "all" || device.location === filterLocation
    const matchesSearch = device.name.toLowerCase().includes(searchQuery.toLowerCase())
    return matchesType && matchesLocation && matchesSearch
  })

  return (
    <DashboardLayout>
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <h1 className="text-2xl font-bold">设备管理</h1>
          <div className="flex gap-2">
            <Button variant="outline" size="sm">
              <RefreshCwIcon className="h-4 w-4 mr-2" />
              刷新
            </Button>
            <Dialog>
              <DialogTrigger asChild>
                <Button size="sm">
                  <PlusIcon className="h-4 w-4 mr-2" />
                  添加设备
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>添加新设备</DialogTitle>
                  <DialogDescription>填写设备信息以添加新的灌溉设备或传感器</DialogDescription>
                </DialogHeader>
                <div className="grid gap-4 py-4">
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="name" className="text-right">
                      设备名称
                    </Label>
                    <Input id="name" className="col-span-3" />
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="type" className="text-right">
                      设备类型
                    </Label>
                    <Select>
                      <SelectTrigger id="type" className="col-span-3">
                        <SelectValue placeholder="选择设备类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="pump">水泵</SelectItem>
                        <SelectItem value="valve">电磁阀</SelectItem>
                        <SelectItem value="fertilizer">施肥机</SelectItem>
                        <SelectItem value="sensor">传感器</SelectItem>
                        <SelectItem value="weather">气象站</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="location" className="text-right">
                      安装位置
                    </Label>
                    <Select>
                      <SelectTrigger id="location" className="col-span-3">
                        <SelectValue placeholder="选择安装位置" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="1号农田">1号农田</SelectItem>
                        <SelectItem value="2号农田">2号农田</SelectItem>
                        <SelectItem value="农场中心">农场中心</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="grid grid-cols-4 items-center gap-4">
                    <Label htmlFor="ip" className="text-right">
                      设备IP
                    </Label>
                    <Input id="ip" className="col-span-3" placeholder="192.168.1.100" />
                  </div>
                </div>
                <DialogFooter>
                  <Button type="submit">添加设备</Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>
        </div>

        <Card>
          <CardHeader className="pb-3">
            <CardTitle>设备列表</CardTitle>
            <CardDescription>管理和控制所有灌溉系统设备</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col md:flex-row gap-4 mb-6">
              <div className="relative flex-1">
                <SearchIcon className="absolute left-2.5 top-2.5 h-4 w-4 text-gray-500" />
                <Input
                  placeholder="搜索设备..."
                  className="pl-8"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
              <Select value={filterType} onValueChange={setFilterType}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="设备类型" />
                </SelectTrigger>
                <SelectContent>
                  {deviceTypes.map((type) => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={filterLocation} onValueChange={setFilterLocation}>
                <SelectTrigger className="w-[180px]">
                  <SelectValue placeholder="安装位置" />
                </SelectTrigger>
                <SelectContent>
                  {locations.map((location) => (
                    <SelectItem key={location.value} value={location.value}>
                      {location.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <Tabs defaultValue="list">
              <TabsList className="mb-4">
                <TabsTrigger value="list">列表视图</TabsTrigger>
                <TabsTrigger value="grid">网格视图</TabsTrigger>
              </TabsList>

              <TabsContent value="list">
                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>设备名称</TableHead>
                        <TableHead>类型</TableHead>
                        <TableHead>位置</TableHead>
                        <TableHead>状态</TableHead>
                        <TableHead>最近活动</TableHead>
                        <TableHead>电量/信号</TableHead>
                        <TableHead className="text-right">操作</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredDevices.map((device) => (
                        <TableRow key={device.id}>
                          <TableCell className="font-medium">{device.name}</TableCell>
                          <TableCell>
                            {device.type === "pump" && "水泵"}
                            {device.type === "valve" && "电磁阀"}
                            {device.type === "fertilizer" && "施肥机"}
                            {device.type === "sensor" && "传感器"}
                            {device.type === "weather" && "气象站"}
                          </TableCell>
                          <TableCell>{device.location}</TableCell>
                          <TableCell>
                            <div className="flex items-center">
                              <div
                                className={`w-2 h-2 rounded-full mr-2 ${
                                  device.status === "online"
                                    ? "bg-green-500"
                                    : device.status === "warning"
                                      ? "bg-amber-500"
                                      : "bg-red-500"
                                }`}
                              ></div>
                              <span>
                                {device.status === "online" ? "在线" : device.status === "warning" ? "警告" : "离线"}
                              </span>
                            </div>
                          </TableCell>
                          <TableCell>{device.lastActive}</TableCell>
                          <TableCell>
                            <div className="flex items-center space-x-2">
                              <div className="flex items-center">
                                <BatteryMediumIcon className="h-4 w-4 mr-1 text-gray-500" />
                                <span
                                  className={`text-xs ${
                                    device.batteryLevel < 20
                                      ? "text-red-500"
                                      : device.batteryLevel < 50
                                        ? "text-amber-500"
                                        : "text-green-500"
                                  }`}
                                >
                                  {device.batteryLevel}%
                                </span>
                              </div>
                              <div className="flex items-center">
                                <WifiIcon className="h-4 w-4 mr-1 text-gray-500" />
                                <span
                                  className={`text-xs ${
                                    device.signalStrength === "none"
                                      ? "text-red-500"
                                      : device.signalStrength === "weak"
                                        ? "text-amber-500"
                                        : "text-green-500"
                                  }`}
                                >
                                  {device.signalStrength === "strong" && "强"}
                                  {device.signalStrength === "medium" && "中"}
                                  {device.signalStrength === "weak" && "弱"}
                                  {device.signalStrength === "none" && "无"}
                                </span>
                              </div>
                            </div>
                          </TableCell>
                          <TableCell className="text-right">
                            <div className="flex justify-end gap-2">
                              {(device.type === "pump" || device.type === "valve" || device.type === "fertilizer") && (
                                <Button
                                  variant={device.isRunning ? "destructive" : "default"}
                                  size="sm"
                                  onClick={() => toggleDevice(device.id)}
                                  disabled={device.status === "offline"}
                                >
                                  {device.isRunning ? (
                                    <>
                                      <PauseIcon className="h-4 w-4 mr-1" /> 停止
                                    </>
                                  ) : (
                                    <>
                                      <PlayIcon className="h-4 w-4 mr-1" /> 启动
                                    </>
                                  )}
                                </Button>
                              )}
                              <Button variant="outline" size="sm">
                                <SettingsIcon className="h-4 w-4" />
                                <span className="sr-only">设置</span>
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </TabsContent>

              <TabsContent value="grid">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {filteredDevices.map((device) => (
                    <Card key={device.id} className="overflow-hidden">
                      <CardHeader className="pb-2">
                        <div className="flex justify-between items-start">
                          <div>
                            <CardTitle className="text-base">{device.name}</CardTitle>
                            <CardDescription>{device.location}</CardDescription>
                          </div>
                          <Badge
                            variant={
                              device.status === "online"
                                ? "default"
                                : device.status === "warning"
                                  ? "outline"
                                  : "destructive"
                            }
                          >
                            {device.status === "online" ? "在线" : device.status === "warning" ? "警告" : "离线"}
                          </Badge>
                        </div>
                      </CardHeader>
                      <CardContent>
                        <div className="flex justify-between items-center mb-4">
                          <div className="flex items-center">
                            <div className="bg-gray-100 p-2 rounded-full mr-3">
                              {device.type === "pump" && <DropletIcon className="h-5 w-5 text-blue-500" />}
                              {device.type === "valve" && <DropletIcon className="h-5 w-5 text-green-500" />}
                              {device.type === "fertilizer" && <LeafIcon className="h-5 w-5 text-green-500" />}
                              {device.type === "sensor" && <BarChart3Icon className="h-5 w-5 text-purple-500" />}
                              {device.type === "weather" && <CloudIcon className="h-5 w-5 text-blue-500" />}
                            </div>
                            <div>
                              <p className="text-sm font-medium">
                                {device.type === "pump" && "水泵"}
                                {device.type === "valve" && "电磁阀"}
                                {device.type === "fertilizer" && "施肥机"}
                                {device.type === "sensor" && "传感器"}
                                {device.type === "weather" && "气象站"}
                              </p>
                              <p className="text-xs text-gray-500">{device.lastActive}</p>
                            </div>
                          </div>
                          <div className="flex flex-col items-end">
                            <div className="flex items-center mb-1">
                              <BatteryMediumIcon className="h-4 w-4 mr-1 text-gray-500" />
                              <span
                                className={`text-xs ${
                                  device.batteryLevel < 20
                                    ? "text-red-500"
                                    : device.batteryLevel < 50
                                      ? "text-amber-500"
                                      : "text-green-500"
                                }`}
                              >
                                {device.batteryLevel}%
                              </span>
                            </div>
                            <div className="flex items-center">
                              <WifiIcon className="h-4 w-4 mr-1 text-gray-500" />
                              <span
                                className={`text-xs ${
                                  device.signalStrength === "none"
                                    ? "text-red-500"
                                    : device.signalStrength === "weak"
                                      ? "text-amber-500"
                                      : "text-green-500"
                                }`}
                              >
                                {device.signalStrength === "strong" && "强"}
                                {device.signalStrength === "medium" && "中"}
                                {device.signalStrength === "weak" && "弱"}
                                {device.signalStrength === "none" && "无"}
                              </span>
                            </div>
                          </div>
                        </div>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center">
                            {device.isRunning ? (
                              <CheckCircleIcon className="h-4 w-4 text-green-500 mr-1" />
                            ) : (
                              <XCircleIcon className="h-4 w-4 text-gray-400 mr-1" />
                            )}
                            <span className="text-sm">{device.isRunning ? "运行中" : "已停止"}</span>
                          </div>
                          {device.status === "warning" && (
                            <div className="flex items-center text-amber-500 text-sm">
                              <AlertTriangleIcon className="h-4 w-4 mr-1" />
                              <span>需要检查</span>
                            </div>
                          )}
                        </div>
                      </CardContent>
                      <CardFooter className="bg-gray-50 flex justify-between">
                        {device.type === "pump" || device.type === "valve" || device.type === "fertilizer" ? (
                          <Button
                            variant={device.isRunning ? "destructive" : "default"}
                            size="sm"
                            onClick={() => toggleDevice(device.id)}
                            disabled={device.status === "offline"}
                            className="w-full"
                          >
                            {device.isRunning ? (
                              <>
                                <PauseIcon className="h-4 w-4 mr-1" /> 停止
                              </>
                            ) : (
                              <>
                                <PlayIcon className="h-4 w-4 mr-1" /> 启动
                              </>
                            )}
                          </Button>
                        ) : (
                          <Button variant="outline" size="sm" className="w-full">
                            <BarChart3Icon className="h-4 w-4 mr-1" /> 查看数据
                          </Button>
                        )}
                      </CardFooter>
                    </Card>
                  ))}
                </div>
              </TabsContent>
            </Tabs>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  )
}
